package com.mzmarket.market.module.service;

import com.mzmarket.market.module.entity.Category;
import com.mzmarket.market.module.entity.Product;
import com.mzmarket.market.module.mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ProductService {

    @Resource
    private ProductMapper productMapper;

    @Autowired
    private CategoryService categoryService;

    public Product getById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return productMapper.getById(id);
    }

    public Product extractById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return productMapper.extractById(id);
    }

    int insert(Product product) {
        return productMapper.insert(product);
    }

    int update(Product product) {
        return productMapper.update(product);
    }

    public int delete(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        } else {
            if (getById(id) == null) {
                throw new RuntimeException("Product not found");
            }
        }
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        return productMapper.delete(id, timeStamp);
    }

    public Long edit(Long id, String title, String images, String description, Integer saleNum, Double price,
                     Long categoryId, Integer favoriteNum) throws RuntimeException {
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        Product product = new Product();

        product.setTitle(title);
        product.setImages(images);
        product.setDescription(description);
        product.setSaleNum(saleNum);
        product.setPrice(price);
        product.setFavoriteNum(favoriteNum);
        product.setIsDeleted(0);
        if (categoryId != null) {
            Category category = null;//categoryId参数存在,执行insert和update功能时需判断获取分类getById是否正常，如果正常执行判断是否该分类存在
            try {
                category = categoryService.getById(categoryId);
            } catch (Exception e) {
                log.warn(e.getMessage());
                throw new RuntimeException("Category get failed");
            }
            if (category == null) {
                throw new RuntimeException("Category not found");
            } else {
                product.setCategoryId(categoryId);
            }
        }

        if (id == null) {//插入业务需要判断每一项不为空
            if (title == null || title.trim().isEmpty()) {
                throw new RuntimeException("Title cannot be null or empty");
            }
            if (images == null || images.trim().isEmpty()) {
                throw new RuntimeException("Images cannot be null or empty");
            }
            if (description == null || description.trim().isEmpty()) {
                throw new RuntimeException("Description cannot be null or empty");
            }
            if (saleNum == null || saleNum < 0) {
                throw new RuntimeException("Sale number must be non-negative");
            }
            if (price == null || price <= 0) {
                throw new RuntimeException("Price must be greater than zero");
            }
            if (favoriteNum == null || favoriteNum < 0) {
                throw new RuntimeException("Favorite number must be non-negative");
            }
            if (categoryId == null) {
                throw new RuntimeException("CategoryID must be input");
            }
            product.setCreateTime(timeStamp);
            insert(product);
        } else {
            product.setId(id);
            if (getById(id) == null) {
                throw new RuntimeException("Product not found");
            } else {
                update(product);
            }
        }
        return product.getId();
    }

    public List<Product> getAll() {
        return productMapper.getAll();
    }

    public Long count(String keyword) {
        return productMapper.count(keyword);
    }

    public List<Product> getPageList(Integer pageSize, Long page, String keyword, String module) {
        if (page == null) {
            throw new RuntimeException("No Page Input");
        }

        Long offset = (page - 1) * pageSize;
        List<Product> pageList = null;
        if (module.equals("console")) {//区分是什么模块
            pageList = productMapper.getPageList(pageSize, offset, keyword);
        }else{
            List<Long> categoryLikeList = productMapper.getCategoryLikeId(keyword);
            StringBuffer sb = new StringBuffer();

            for (int i = 0; i < categoryLikeList.size(); i++) {
                sb.append(categoryLikeList.get(i));
                if (i < categoryLikeList.size() - 1) {
                    sb.append(",");
                }
            }
            pageList = productMapper.getPageList2(pageSize, offset, keyword, sb.toString());
        }

        for (Product product : pageList) {//遍历列表防止数据库存在脏数据
            Category category = null;
            try {
                category = categoryService.getById(product.getCategoryId());
            } catch (Exception e) {
                throw new RuntimeException("Category get fail");
            }
            if (category == null) {
                throw new RuntimeException("Category not found");
            }
        }

        return pageList;
    }
}
